package com.example.modules.common.config.serviceimpl;

import com.example.modules.common.config.service.RedisService;
import com.newtouch.aiplatform.core.utils.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * redis缓存操作ServiceImpl
 * 
 * @author zbq
 * @date 2018-06-08 15:08:53
 * @version 1.0
 * @see RedisService
 */
@Service
public class RedisServiceImpl implements RedisService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Resource(name = "stringRedisTemplate")
	private ValueOperations<String, String> valueOperations;

	@Override
	public void set(String key, Object obj) {
		set(key, obj, null, null);
	}

	@Override
	public void set(String key, Object obj, final Long timeout, final TimeUnit timeUnit) {
		String jsonStr = "";
		if (obj instanceof String) {
			jsonStr = (String) obj;
		} else {
			jsonStr = JSONUtil.toJson(obj);
		}
		if (timeout != null && timeUnit != null) {
			valueOperations.set(key, jsonStr, timeout, timeUnit);
		} else {
			valueOperations.set(key, jsonStr);
		}
	}

	@Override
	public void delete(String key) {
		redisTemplate.delete(key);
	}

	@Override
	public void delete(List<String> keys) {
		redisTemplate.delete(keys);
	}

	@Override
	public <T> T get(String key, Class<T> clazz) {
		return get(key, clazz, null, null);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T get(String key, Class<T> clazz, Long start, Long end) {
		T obj = null;
		String jsonStr = getJson(key, start, end);
		if (StringUtils.isNotBlank(jsonStr)) {
			if (clazz.equals(String.class)) {
				obj = (T) jsonStr;
			} else {
				obj = JSONUtil.toObject(jsonStr, clazz);
			}
		}
		return obj;
	}

	@Override
	public <T> List<T> getList(String key, Class<T> clazz) {
		return getList(key, clazz, null, null);
	}

	@Override
	public <T> List<T> getList(String key, Class<T> clazz, Long start, Long end) {
		List<T> objList = null;
		String jsonStr = getJson(key, start, end);
		if (StringUtils.isNotBlank(jsonStr)) {
			objList = JSONUtil.toObjectList(jsonStr, clazz);
		}
		return objList;
	}

	/**
	 * 获取字符串
	 * 
	 * @param key
	 *            key
	 * @param start
	 *            开始位置
	 * @param end
	 *            结束位置
	 * @return String
	 */
	private String getJson(String key, Long start, Long end) {
		String jsonStr = "";
		if (redisTemplate.hasKey(key)) {
			if (start != null && end != null) {
				jsonStr = valueOperations.get(key, start, end);
			} else {
				jsonStr = valueOperations.get(key);
			}
		}
		return jsonStr;
	}
}
